﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CoVanHocTapData.Entities;
using CrystalDecisions.CrystalReports.Engine;
using CoVanHocTapData.Concretes;
using CoVanHocTapProject.Infrastructure;
using System.IO;

namespace CoVanHocTapProject.Controllers
{
    public class ReportController : Controller
    {
        //
        // GET: /Report/

        public ActionResult Index()
        {
            return View();
        }

        //public ActionResult Report()
        //{
        //    return View();
        //}

        //[HttpPost]
        public ActionResult ReportMonHoc()
        {
            if (Publics.adminDangNhap == null)
                return View();
            MonHocSinhVienDangKyKHHTRepository repos = new MonHocSinhVienDangKyKHHTRepository();
            NganhDaoTaoRepository nganhRepos = new NganhDaoTaoRepository();
            KhoaRepository khoaRepos = new KhoaRepository();

            ReportClass rptH = new ReportClass();
            rptH.FileName = Server.MapPath("/Reports/BaoCaoMonHocDangKy.rpt");
            rptH.Load();

            List<MonHocSinhVienDangKyKHHT> result = new List<MonHocSinhVienDangKyKHHT>();

            var khoaList = khoaRepos.LayTatCaKhoa();
            foreach (var khoaItem in khoaList)
            {
                var nganhList = nganhRepos.LayNganhDaoTao(khoaItem.KhoaID);
                foreach (var nganhItem in nganhList)
                {
                    var temp =  repos.LayDanhSachSinhVienDangKy(Publics.hocKyHienTai, khoaItem.TenKhoa, nganhItem.TenNganh);
                    foreach (var tempItem in temp)
                    {
                        result.Add(tempItem);
                    }
                }
            }

            rptH.SetDataSource(result);
            Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

            //string saveTo = Server.MapPath("/ReportFile/demo.pdf");
            //FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.Write);
            //ReadWriteStream(stream, writeStream);
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AppendHeader("charset", "utf-8");
            return File(stream, "application/pdf");

            //return View();
        }

    }
}
